import request from '@/utils/request'

// 课程相关类型定义
export interface Course {
  id: number
  title: string
  description: string
  content?: string
  type: 'video' | 'document' | 'mixed'
  difficulty: 'beginner' | 'medium' | 'advanced'
  category: string
  tags?: string
  video_url?: string
  video_id?: string
  video_source?: string
  duration: number
  thumbnail_url?: string
  instructor: string
  instructor_id: number
  language: string
  status: 'draft' | 'published' | 'archived'
  view_count: number
  enroll_count: number
  like_count: number
  rating: number
  rating_count: number
  created_at: string
  updated_at: string
  user_info?: {
    is_enrolled: boolean
    enrollment_status: string
    progress: number
    is_completed: boolean
    is_favorited: boolean
  }
  // 用户相关状态（用于用户课程列表）
  progress?: number
  is_favorited?: boolean
  is_enrolled?: boolean
  is_completed?: boolean
}

export interface CourseEnrollment {
  id: number
  user_id: number
  course_id: number
  status: 'enrolled' | 'completed' | 'dropped'
  progress: number
  enrolled_at: string
  completed_at?: string
  last_watched_at?: string
  created_at: string
  updated_at: string
}

export interface CourseComment {
  id: number
  user_id: number
  course_id: number
  content: string
  rating: number
  parent_id?: number
  like_count: number
  status: string
  created_at: string
  updated_at: string
  user: {
    id: number
    username: string
    avatar_url: string
  }
  replies?: CourseComment[]
}

export interface CourseRating {
  id: number
  user_id: number
  course_id: number
  rating: number
  comment?: string
  created_at: string
  updated_at: string
}

export interface CourseListParams {
  page?: number
  page_size?: number
  category?: string
  difficulty?: string
  type?: string
  status?: string
  search?: string
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

export interface CourseListResponse {
  items: Course[]
  total: number
  page: number
  page_size: number
  total_pages: number
}

export interface UserCourseStats {
  total_courses: number
  completed_courses: number
  in_progress_courses: number
  total_hours: number
}

export interface CreateCourseRequest {
  title: string
  description?: string
  content?: string
  type: 'video' | 'document' | 'mixed'
  difficulty: 'beginner' | 'medium' | 'advanced'
  category: string
  tags?: string
  video_url?: string
  video_id?: string
  video_source?: string
  duration?: number
  thumbnail_url?: string
  instructor: string
  language?: string
}

export interface UpdateCourseRequest {
  title?: string
  description?: string
  content?: string
  type?: 'video' | 'document' | 'mixed'
  difficulty?: 'beginner' | 'medium' | 'advanced'
  category?: string
  tags?: string
  video_url?: string
  video_id?: string
  video_source?: string
  duration?: number
  thumbnail_url?: string
  instructor?: string
  language?: string
  status?: 'draft' | 'published' | 'archived'
}

export interface EnrollCourseRequest {
  course_id: number
}

export interface RateCourseRequest {
  rating: number
  comment?: string
}

export interface CommentCourseRequest {
  content: string
  rating?: number
  parent_id?: number
}

export interface UpdateProgressRequest {
  progress: number
}

// 课程API类
export class CourseAPI {
  // 获取课程列表
  static async getCourses(params?: CourseListParams): Promise<CourseListResponse> {
    return request.get('/v1/courses', { params })
  }

  // 获取课程详情
  static async getCourse(id: number): Promise<Course> {
    return request.get(`/v1/courses/${id}`)
  }

  // 创建课程
  static async createCourse(data: CreateCourseRequest): Promise<{ id: number }> {
    return request.post('/v1/courses', data)
  }

  // 更新课程
  static async updateCourse(id: number, data: UpdateCourseRequest): Promise<void> {
    return request.put(`/v1/courses/${id}`, data)
  }

  // 删除课程
  static async deleteCourse(id: number): Promise<void> {
    return request.delete(`/v1/courses/${id}`)
  }

  // 报名课程
  static async enrollCourse(data: EnrollCourseRequest): Promise<void> {
    return request.post(`/v1/courses/${data.course_id}/enroll`, {})
  }

  // 评分课程
  static async rateCourse(id: number, data: RateCourseRequest): Promise<void> {
    return request.post(`/v1/courses/${id}/rate`, data)
  }

  // 评论课程
  static async commentCourse(id: number, data: CommentCourseRequest): Promise<{ comment_id: number }> {
    return request.post(`/v1/courses/${id}/comment`, data)
  }

  // 获取课程评论
  static async getCourseComments(id: number, page = 1, pageSize = 10): Promise<CourseListResponse> {
    return request.get(`/v1/courses/${id}/comments`, {
      params: { page, page_size: pageSize }
    })
  }

  // 切换课程收藏状态
  static async toggleCourseFavorite(id: number): Promise<void> {
    return request.post(`/v1/courses/${id}/favorite`)
  }

  // 更新课程学习进度
  static async updateCourseProgress(id: number, data: UpdateProgressRequest): Promise<void> {
    return request.put(`/v1/courses/${id}/progress`, data)
  }

  // 获取用户课程列表
  static async getUserCourses(userId: number, params?: CourseListParams): Promise<CourseListResponse> {
    return request.get(`/v1/users/${userId}/courses`, { params })
  }

  // 获取用户课程统计
  static async getUserCourseStats(userId: number): Promise<UserCourseStats> {
    return request.get(`/v1/users/${userId}/courses/stats`)
  }

  // 下载课程资料（如果有的话）
  static async downloadCourseMaterials(id: number): Promise<void> {
    return request.get(`/v1/courses/${id}/materials`, {
      responseType: 'blob'
    })
  }

  // 获取视频嵌入URL
  static getVideoEmbedURL(course: Course): string {
    if (!course.video_id || !course.video_source) {
      return course.video_url || ''
    }

    switch (course.video_source) {
      case 'bilibili':
        return `https://player.bilibili.com/player.html?bvid=${course.video_id}`
      case 'youtube':
        return `https://www.youtube.com/embed/${course.video_id}`
      default:
        return course.video_url || ''
    }
  }

  // 获取视频缩略图URL
  static getVideoThumbnail(course: Course): string {
    if (course.thumbnail_url) {
      return course.thumbnail_url
    }

    if (!course.video_id || !course.video_source) {
      return ''
    }

    switch (course.video_source) {
      case 'bilibili':
        // B站缩略图需要通过API获取，这里返回一个占位符
        return `https://api.bilibili.com/x/web-interface/view?bvid=${course.video_id}`
      case 'youtube':
        return `https://img.youtube.com/vi/${course.video_id}/maxresdefault.jpg`
      default:
        return ''
    }
  }

  // 解析B站视频ID
  static parseBilibiliVideoId(url: string): string | null {
    // 支持多种B站URL格式
    const patterns = [
      /bilibili\.com\/video\/([a-zA-Z0-9]+)/,
      /b23\.tv\/([a-zA-Z0-9]+)/,
      /bilibili\.com\/video\/BV([a-zA-Z0-9]+)/,
    ]

    for (const pattern of patterns) {
      const match = url.match(pattern)
      if (match) {
        return match[1].startsWith('BV') ? match[1] : `BV${match[1]}`
      }
    }

    return null
  }

  // 解析YouTube视频ID
  static parseYouTubeVideoId(url: string): string | null {
    const patterns = [
      /youtube\.com\/watch\?v=([a-zA-Z0-9_-]+)/,
      /youtu\.be\/([a-zA-Z0-9_-]+)/,
      /youtube\.com\/embed\/([a-zA-Z0-9_-]+)/,
    ]

    for (const pattern of patterns) {
      const match = url.match(pattern)
      if (match) {
        return match[1]
      }
    }

    return null
  }

  // 验证视频URL并提取信息
  static parseVideoUrl(url: string): { source: string; videoId: string } | null {
    if (!url) return null

    // 检查B站
    const bilibiliId = this.parseBilibiliVideoId(url)
    if (bilibiliId) {
      return { source: 'bilibili', videoId: bilibiliId }
    }

    // 检查YouTube
    const youtubeId = this.parseYouTubeVideoId(url)
    if (youtubeId) {
      return { source: 'youtube', videoId: youtubeId }
    }

    return null
  }

  // 格式化课程时长
  static formatDuration(minutes: number): string {
    if (minutes < 60) {
      return `${minutes}分钟`
    }
    const hours = Math.floor(minutes / 60)
    const remainingMinutes = minutes % 60
    if (remainingMinutes === 0) {
      return `${hours}小时`
    }
    return `${hours}小时${remainingMinutes}分钟`
  }

  // 格式化课程难度
  static formatDifficulty(difficulty: string): string {
    const difficultyMap: Record<string, string> = {
      beginner: '初级',
      medium: '中级',
      advanced: '高级'
    }
    return difficultyMap[difficulty] || difficulty
  }

  // 格式化课程类型
  static formatType(type: string): string {
    const typeMap: Record<string, string> = {
      video: '视频课程',
      document: '文档课程',
      mixed: '混合课程'
    }
    return typeMap[type] || type
  }

  // 格式化课程状态
  static formatStatus(status: string): string {
    const statusMap: Record<string, string> = {
      draft: '草稿',
      published: '已发布',
      archived: '已归档'
    }
    return statusMap[status] || status
  }

  // 格式化报名状态
  static formatEnrollmentStatus(status: string): string {
    const statusMap: Record<string, string> = {
      enrolled: '已报名',
      completed: '已完成',
      dropped: '已退出',
      not_enrolled: '未报名'
    }
    return statusMap[status] || status
  }
}

// 导出默认实例
export const courseApi = CourseAPI